<template>
  <el-card>
    <div class="BigOne">
      <el-button type="success" class="NavButton el-icon-edit" @click="$router.push('new')">新增试题</el-button>
    </div>
    <div class="BigTwo">
      <el-row :gutter="1" class="NavBar">
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">学科</span>
            <el-select placeholder="请选择" v-model="requestParams.subjectID" @change="changeSubject">
              <el-option v-for="item in gitList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div></el-col>
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">二级目录</span>
          <el-select placeholder="请选择" v-model="requestParams.catalogID">
              <el-option v-for="item in directoryOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div></el-col>
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">标签</span>
          <el-select placeholder="请选择" v-model="requestParams.tagScript">
              <el-option v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div></el-col>
          <el-col :span="6" style="height:35px">
            <el-form>
            <el-form-item >
              <span class="demonstration" style="font-size: 16px">关键字</span>
              <el-input v-model="requestParams.keyword" style="width: 221px"></el-input>
            </el-form-item>
          </el-form>
          </el-col>
      </el-row>
      <el-row :gutter="1" class="TurnRan">
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">试题类型</span>
          <el-select placeholder="请选择" v-model="requestParams.questionType">
              <el-option v-for="item in questionTypeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div></el-col>
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">难度</span>
          <el-select placeholder="请选择" v-model="requestParams.difficulty">
              <el-option v-for="item in diffOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div></el-col>
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">方向</span>
          <el-select placeholder="请选择" v-model="requestParams.direction">
              <el-option v-for="item in direcOptions" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </div></el-col>
        <el-col :span="6"><div class="grid-content bg-purple">
          <span class="demonstration">录入人</span>
          <el-select placeholder="请选择" v-model="requestParams.creatorID">
              <el-option v-for="item in userOptions" :key="item.id" :label="item.username" :value="item.id">
              </el-option>
            </el-select>
          </div></el-col>
      </el-row>
      <el-row :gutter="1" class="Shift">
        <el-col :span="6" style="height:35px">
            <el-form>
            <el-form-item >
              <span class="demonstration">题目备注</span>
              <el-input v-model="requestParams.remarks" style="width: 230px"></el-input>
            </el-form-item>
          </el-form>
          </el-col>
        <el-col :span="6" style="height:35px">
            <el-form>
            <el-form-item >
              <span class="demonstration">企业简称</span>
              <el-input v-model="requestParams.shortName" style="width: 230px"></el-input>
            </el-form-item>
          </el-form>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple BigThree">
              <span class="demonstration">城市</span>
              <el-select placeholder="请选择" class="block" v-model="requestParams.province" @change="hanldrank">
                  <el-option v-for="item in cityOptions" :key="item" :label="item" :value="item">
                  </el-option>
              </el-select>
              <el-select placeholder="请选择" class="block" v-model="requestParams.city">
                  <el-option v-for="item in areaOptions" :key="item" :label="item" :value="item">
                  </el-option>
              </el-select>
            </div>
          </el-col>
          <div class="NavDiv">
            <el-button @click="clear()">清除</el-button>
            <el-button type="primary" @click="filter">搜索</el-button>
          </div>
      </el-row>
    </div>
    <el-tabs type="card" class="MaginTop" v-model="requestParams.chkState" @tab-click="changeTab">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待审核" name="0"></el-tab-pane>
      <el-tab-pane label="已审核" name="1"></el-tab-pane>
      <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
  </el-tabs>
  <el-alert
        :title="`数据一共 ${total} 条`"
        style="margin-bottom:15px"
        type="info"
        class="alert"
        show-icon
  ></el-alert>
  <el-table
    :data="requestChoice"
    border
    style="width: 100%">
    <el-table-column fixed prop="number" label="试题编号" width="120">
    </el-table-column>
    <el-table-column prop="subject" label="学科" width="120">
    </el-table-column>
    <el-table-column prop="catalog" label="目录" width="120">
    </el-table-column>
    <el-table-column label="题型" width="120">
      <template #default="{row}">
        {{questionType.find(item => item.value === +row.questionType).label}}
      </template>
    </el-table-column>
    <el-table-column label="题干" width="250">
      <template #default="{row}">
        <div v-html="row.question"></div>
      </template>
    </el-table-column>
    <el-table-column prop="chkDate" label="录入时间" width="120">
      <template #default="{row}">
        {{row.addDate|parseTimeByString}}
      </template>
    </el-table-column>
    <el-table-column prop="difficulty" label="难度" width="120">
      <template #default="{row}">
        {{difficulty.find(item => item.value === +row.difficulty).label}}
      </template>
    </el-table-column>
    <el-table-column prop="creator" label="录入人" width="120"></el-table-column>
    <el-table-column
      fixed="right"
      label="操作"
      width="300">
      <template slot-scope="scope">
        <el-button class="fs" type="text" @click="openPreviewDialog(scope.row)">预览</el-button>
        <el-button type="text" size="small" @click="openCheckDialog(scope.row)" :disabled="scope.row.chkState!==0">审核</el-button>
        <el-button type="text" size="small" :disabled="scope.row.publishState===1" @click="$router.push(`new?id=${scope.row.id}`)">修改</el-button>
        <el-button type="text" size="small" @click="togglePublish(scope.row)">{{scope.row.publishState===1?'下架':'上架'}}</el-button>
        <el-button type="text" size="small" :disabled="scope.row.publishState===1" @click="delQuestion(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
        style="margin-top:20px;text-align:right"
        background
        layout="prev, pager, next, sizes, jumper"
        :total="total"
        :page-size="requestParams.pagesize"
        :current-page="requestParams.page"
        @current-change="pager"
        :page-sizes="[5,10,20,50]"
        @size-change="handleSizeChange"
   ></el-pagination>
  <QuestionsPreview ref="questionPreview" :data="questionInfo"></QuestionsPreview>
  <QuestionsCheck ref="questionCheck" :data="questionInfo" @updateList="getList()"></QuestionsCheck>
  </el-card>
</template>

<script>
import { simple as subjectList } from '@/api/hmmm/subjects'
import { simple as directoryList } from '@/api/hmmm/directorys'
import { simple as tagList } from '@/api/hmmm/tags'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { simple as userList } from '@/api/base/users'
import { provinces as getCity, citys as getArea } from '@/api/hmmm/citys'
import { choice as requestChoice, choicePublish, remove } from '@/api/hmmm/questions'
import QuestionsPreview from '../components/questions-preview.vue'
import QuestionsCheck from '../components/questions-check.vue'
export default {
  name: 'questionsChoice',
  components: {
    QuestionsPreview,
    QuestionsCheck
  },
  filters: {
    state_chk (val) {
      if (val === 0) return '待审核'
      if (val === 1) return '已审核'
      if (val === 2) return '已拒绝'
    },
    state_pub (row) {
      if (row.publishState === 1 && row.chkState === 1) {
        return '已发布'
      }
      if (row.publishState === 0 && row.chkState === 1) {
        return '已下架'
      }
      return '待发布'
    }
  },
  data () {
    return {
      chargehand: [],
      questionInfo: {},
      gitList: [],
      total: 0,
      requestChoice: [],
      tagOptions: [],
      directoryOptions: [],
      direcOptions: direction,
      diffOptions: difficulty,
      questionType,
      difficulty,
      questionTypeOptions: questionType,
      requestParams: {
        subjectID: null,
        catalogID: null,
        tagScript: null,
        questionType: null,
        difficulty: null,
        direction: null,
        creatorID: null,
        keyword: null,
        remarks: null,
        province: null,
        city: null,
        shortName: null,
        page: 1,
        pagesize: 5,
        chkState: 'all'
      },
      userOptions: [],
      cityOptions: getCity(),
      areaOptions: []
    }
  },
  async created () {
    const { data } = await subjectList()
    // console.log(data)
    this.gitList = data
    // console.log(this.gitList)
    // console.log(this.cityOptions)

    const result = await userList()
    console.log(result.data)
    this.userOptions = result.data

    // const res = await requestChoice(this.requestParams)
    // console.log(res.data)
    // this.requestChoice = res.data.items
    // this.total = res.data.counts
    this.searchList()
  },
  methods: {
    async changeSubject (subjectID) {
      this.catalogID = null
      this.tags = null
      if (subjectID) {
        const { data: directoryArr } = await directoryList({ subjectID })
        this.directoryOptions = directoryArr
        const { data: tagArr } = await tagList({ subjectID })
        this.tagOptions = tagArr
      } else {
        this.directoryOptions = []
        this.tagOptions = []
      }
    },
    async searchList () {
      const res = await requestChoice()
      console.log(res.data)
      this.requestChoice = res.data.items
      this.total = res.data.counts
    },
    async filter () {
      const obj = {}
      for (const key in this.requestParams) {
        if (this.requestParams[key]) {
          obj[key] = this.requestParams[key]
        }
      }
      console.log(obj)
      const res = await requestChoice(obj)
      console.log(res.data)
      this.requestChoice = res.data.items
      this.total = res.data.counts
    },
    hanldrank (cityName) {
      this.city = null
      this.areaOptions = getArea(cityName)
    },
    clear () {
      for (const key in this.requestParams) {
        if (key !== 'page' && key !== 'pagesize') this.requestParams[key] = null
      }
    },
    openPreviewDialog (questionInfo) {
      this.questionInfo = questionInfo
      this.$nextTick(() => {
        this.$refs.questionPreview.open()
      })
    },
    changeTab () {
      this.requestParams.page = 1
      this.getList()
    },
    async getList () {
      const params = { ...this.requestParams }
      if (params.chkState === 'all') params.chkState = null
      const { data: questionsData } = await requestChoice(params)
      console.log(questionsData)
      this.requestChoice = questionsData.items
      this.total = questionsData.counts
    },
    // async filter () {
    //   for (const key in this.requestParams) {
    //     const res = {}
    //     if (this.requestParams[key]) {
    //       // console.log(123)
    //       console.log(this.requestParams[key])
    //       res[key] = this.requestParams[key]
    //     }
    //   }
    // },
    handleSizeChange (size) {
      this.requestParams.page = 1
      this.requestParams.pagesize = size
      this.getList()
    },
    pager (np) {
      this.requestParams.page = np
      this.getList()
    },
    handleCity (cityName) {
      this.requestParams.city = null
      this.areaOptions = getArea(cityName)
    },
    openCheckDialog (questionInfo) {
      this.questionInfo = questionInfo
      this.$nextTick(() => {
        this.$refs.questionCheck.open()
      })
    },
    async togglePublish (chargehand) {
      await this.$confirm(`您确认${chargehand.publishState === 1 ? '上架' : '下架'}这道题目吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      chargehand.publishState = chargehand.publishState === 1 ? 0 : 1
      const result = await choicePublish(chargehand)
      console.log(result)
      this.$message.success(`${chargehand.publishState === 1 ? '下架' : '上架'}成功`)
      this.getList()
    },
    delQuestion (question) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await remove(question)
        console.log(res)
        this.getList()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang='less'>
.BigOne {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.NavBar {
  margin-top: 10px;
}
.TurnRan {
  margin-top: 10px;
}
.Shift {
  margin-top: 10px;
}
.NavButton {
  margin-top: 10px;
  margin-right:48px;
}
.BigTwo {
  width: 100%;
}
.demonstration {
  margin-right: 8px;
}
.NavDiv {
  float: right;
  margin-top: 10px;
  margin-right: 48px;
}
.block {
  width: 110px;
  display: inline-block;
}
.MaginTop {
  margin-top: 20px;
}
.fs {
  font-size: 12px;
}
</style>
